package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.CategoryEnum;
import com.qianniu.napi.admin.entity.penum.YXType;
import com.qianniu.napi.admin.mapper.StoreStatMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ImageUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 实体店商家地址，需要满足实体营业执照+店面+独立小程序
 * </p>
 *
 * @author chenxuebin
 * @since 2018-10-16
 */
@Controller
public class StoreController {

    private static final Logger logger = LoggerFactory.getLogger(StoreController.class);

    @Autowired
    private IStoreService storeService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IMerchantAppService merchantAppService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping("admin/store/index")
    public String index(Model model) {

        Wrapper<Config> wrapper = new EntityWrapper<Config>().eq("state", 1);
        MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());

        if (mapp != null && mapp.getVersion() == 4) {
            wrapper.eq("type", CategoryEnum.hangyefenlei.getVal()).eq("mpid", ObjectUtil.getMpid());
        } else {
            wrapper.eq("type", CategoryEnum.businessType.getVal());
        }

        // 店家目录类别
        List<Config> business = configService.selectList(wrapper);
        MerchantConfig mc = redisService.getMconfig();

        logger.info("-----------------------------------store/index version=" + mapp.getVersion());

        model.addAttribute("version", mapp.getVersion());
        model.addAttribute("isDuihuan", mc.getIsDuihuan());
        model.addAttribute("business", business);

        return "admin/store";
    }

    @RequestMapping("/admin/store/list")
    @ResponseBody
    public Page<Store> list(@RequestParam(value = "offset", required = false) Integer offset,
                            @RequestParam(value = "status", required = false) Integer status,
                            @RequestParam(value = "search", required = false) String search,
                            @RequestParam(value = "storetype", required = false) Integer storetype,
                            @RequestParam(value = "limit", required = false) Integer limit
    ) {
        Wrapper<Store> wrapper = new EntityWrapper<Store>();
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());

        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("name", search).or().like("address", search).or().like("linkman", search)
                    .or().like("phone", search).or().like("wxno", search);

        if (storetype != null) wrapper.eq("type", storetype);

        wrapper.orderBy("id", false);
        Page<Store> page = storeService.selectPage(new Page<Store>(offset / limit + 1, limit), wrapper);

        return page;
    }

    @RequestMapping("/admin/store/goodslist")
    @ResponseBody
    public Page<Goods> goodslist(@RequestParam(value = "offset", required = false) Integer offset,
                                 @RequestParam(value = "status", required = false) Integer status,
                                 @RequestParam(value = "search", required = false) String search,
                                 @RequestParam(value = "sid", required = false) String sid,
                                 @RequestParam(value = "limit", required = false) Integer limit
    ) {
        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        wrapper.setSqlSelect("id,name,characteristic,pic,photos,info,sid,jieshao,state,stores,gtype,price,saleprice,jifen")
                .eq("sid", sid);
        wrapper.orderBy("id", false);
        Page<Goods> page = goodsService.selectPage(new Page<Goods>(offset / limit + 1, limit), wrapper);

        return page;
    }

    @RequestMapping("/admin/store/add")
    public String add(@Valid Store bean, BindingResult bindingResult, Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setModifier(ObjectUtil.getUid());
        //bean.setUid(ObjectUtil.getUid());//后台添加上商家
        // 后台添加门店信息 默认通过
        bean.setState(1);
        bean.setStatus(2);
        // 门头照单独设置
//        if (!Strings.isNullOrEmpty(bean.getPhotos())) {
//            List<String> pics = Arrays.asList(bean.getPhotos().split(";"));
//            bean.setPic(pics.get(0));
//        }
        bean.setThumb(bean.getPic());
        bean.insert();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Store@"+bean.getId()+"@insert", ActorRef.noSender());

        StoreStat storeStat = new StoreStat();
        storeStat.setStoreid(bean.getId());
        storeStat.setStorename(bean.getName());
        storeStat.setStorepic(bean.getThumb());
        storeStat.setModifytime(bean.getCreatetime());
        storeStat.setMpid(bean.getMpid());
        storeStat.insertOrUpdate();

        //压缩
        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_MODIFY + "@" + bean.getId(), ActorRef.noSender());


        return "redirect:index";
    }

    @RequestMapping("/admin/store/addgoods")
    public String addgoods(@Valid Goods bean, BindingResult bindingResult, Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());
        // 后台添加门店信息 默认通过
        bean.setType(YXType.jifengou.getVal());
        bean.setState(1);

        if (!Strings.isNullOrEmpty(bean.getPhotos())) {
            List<String> pics = Arrays.asList(bean.getPhotos().split(";"));
            bean.setPic(pics.get(0));
        }
        bean.insert();

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_GOODS_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        return "redirect:index";
    }

    @RequestMapping("/admin/store/modifygoods")
    public String modifygoods(@Valid Goods bean, BindingResult bindingResult, Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        // 后台添加门店信息 默认通过
        bean.setState(1);
        if (!Strings.isNullOrEmpty(bean.getPhotos())) {
            List<String> pics = Arrays.asList(bean.getPhotos().split(";"));
            bean.setPic(pics.get(0));
        }
        bean.updateById();

        return "redirect:index";
    }

    @RequestMapping("/admin/store/getStoreById")
    @ResponseBody
    public Store getStoreById(long id) {
        Store store = storeService.selectById(id);
        return store;
    }

    @RequestMapping("/admin/store/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = storeService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/store/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Store bean = new Store();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        storeService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/store/setauth")
    public String setauth(Store store) {
        store.setModifytime(new Date());
        store.setModifier(ObjectUtil.getUid());
//        if (store.getIsAuth() == 1) {
//            store.setStatus(2);
//        }
//        else {
//            store.setStatus(1);
//        }

        storeService.updateById(store);
        return "redirect:index";
    }

    @RequestMapping("/admin/store/modify")
    public String update(Store bean) {
        logger.info(">>>>>>/admin/store/modify bean=", JSON.toJSONString(bean));
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
//        if (!Strings.isNullOrEmpty(bean.getPhotos())) {
//            List<String> pics = Arrays.asList(bean.getPhotos().split(";"));
//            bean.setPic(pics.get(0));
//        }
        // 需要优化
        bean.setThumb(bean.getPic());
        boolean isSuccc = storeService.updateById(bean);

        StoreStat storeStat = new StoreStat();
        storeStat.setStoreid(bean.getId());
        storeStat.setStorename(bean.getName());
        storeStat.setStorepic(bean.getThumb());
        storeStat.setModifytime(bean.getCreatetime());
        storeStat.setMpid(bean.getMpid());
        storeStat.insertOrUpdate();

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        if (isSuccc) {
            //更新资源文件
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("Store@"+bean.getId()+"@update", ActorRef.noSender());

            return "redirect:index";
        }

        return "redirect:index";
    }

    @RequestMapping("/admin/store/guanlian")
    @ResponseBody
    public Jinfo guanlian(Long sid, String phone) {
        logger.info(">>>>>>/admin/store/guanlian sid=" + sid);
        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        if (mpid == null||mpid == 0) {
            info.setCode(1);
            info.setMsg("当前用户不是平台应用账户");
            return info;
        }

        User user = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,mpid")
                .eq("phone", phone).eq("mpid", mpid));
        if (user == null) {
            info.setCode(4);
            info.setMsg("该手机号用户未在平台注册");
            return info;
        }

        user.setSid(sid);
        user.setIsMch(1);
        user.setIsAdmin(1);
        user.updateById();

        //更新换层
        redisService.delUser(user.getId());

        return info;
    }

    private final static String rootsite = "https://img.niucaiduo.com/";
    @RequestMapping("/admin/store/clearimg")
    @ResponseBody
    public Jinfo clearimg(Long mpid) {
        Jinfo info = new Jinfo();
        if (mpid == null || mpid < 0) return info;
        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        String img = "";
        String type = "store";
        while (flag) {
            Wrapper<Store> wrapper = new EntityWrapper<Store>()
                    .setSqlSelect("id,thumb,pic,photos,xiangqing,zhizhao,xukezheng").eq("mpid", mpid);

            Page page = new Page(index, limit);
            Page<Store> list = storeService.selectPage(page, wrapper);

            logger.debug(">>>>>>>>>>>>>>>>>>checkStoreImage list=" + JSON.toJSONString(list.getRecords()));

            for (Store item : list.getRecords()) {
                logger.info("------------------------------for each start");

                if (!Strings.isNullOrEmpty(item.getThumb())) {
                    img = item.getThumb().replace(rootsite, Constants.PATH_IMAGES);
                    ImageUtil.movebak(img, type);
                }

                if (!Strings.isNullOrEmpty(item.getPic())) {
                    img = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    ImageUtil.movebak(img, type);
                }

                if (!Strings.isNullOrEmpty(item.getPhotos())) {
                    String[] photos = item.getPhotos().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getXiangqing())) {
                    String[] photos = item.getXiangqing().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getZhizhao())) {
                    String[] photos = item.getZhizhao().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getXukezheng())) {
                    String[] photos = item.getXukezheng().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String p : photos) {
                        img = p;
                        ImageUtil.movebak(img, type);
                    }
                }
            }
            flag = list.getRecords() != null && list.getRecords().size() == limit;
            index++;
        }

        ImageUtil.restorebak(img, "store");

        return info;
    }

    @RequestMapping("/admin/store/initmchpwd")
    @ResponseBody
    public Jinfo initmchpwd(long id, String phone) {

        Jinfo jinfo = new Jinfo();
        Store store = storeService.selectById(id);
        if (store == null) {
            jinfo.setCode(4);
            jinfo.setMsg("参数有误");
            return jinfo;
        }
        User muser = userService.selectOne(new EntityWrapper<User>().eq("is_mch",1)
                .eq("sid",id).eq("phone",phone)
        );
        if (muser == null) {
            jinfo.setCode(4);
            jinfo.setMsg("该手机号用户未在小程序端绑定手机号");
            return jinfo;
        }
        MerchantApp mapp = merchantAppService.selectOne(new EntityWrapper<MerchantApp>().eq("id",store.getMpid()));
        String password = Strings.isNullOrEmpty(mapp.getJiancode())? phone:mapp.getJiancode()+phone;

        logger.debug("======new password=" + password);

        muser.setUsername(phone);
        if(muser.getIsAdmin()==null||muser.getIsAdmin()!=1){
            muser.setIsMch(1);
            muser.setIsStaff(1);
            muser.setIsAdmin(-1);
        }else{
            muser.setIsMch(1);
            muser.setIsStaff(-1);
            muser.setIsAdmin(1);
        }

        muser.setModifytime(new Date());
        muser.setState(1);

        muser.setSid(id);

        muser.setUserType(31);// 默认商家专业版
        muser.setPhoto(store.getPic());

        muser.setSalt(muser.getGuid().substring(0, 24));
        muser.setPassword(ObjectUtil.getPwd(password, muser.getSalt(), 3));

        muser.updateById();

        UserRole userrole = new UserRole();
        userrole.setUserid(muser.getId());
        userrole.setRoleid(11l);// 默认1
        userrole.setState(1);// 默认1
        userrole.setMid(mapp.getMid());// 默认1
        userrole.setUid(muser.getId());// 默认1
        userrole.insert();

        String msg = "请牢记账号密码：账号=" + phone + "，密码=" + password;
        jinfo.setInfo(msg);

        return jinfo;
    }


    @RequestMapping("/admin/store/initallmchpwd")
    @ResponseBody
    public Jinfo initallmchpwd(long mpid, String token) {

        Jinfo jinfo = new Jinfo();

        if (!token.equals("huakouyun20202020") ) {
            jinfo.setCode(4);
            jinfo.setMsg("参数有误");
            return jinfo;
        }
        List<User> musers = userService.selectList(new EntityWrapper<User>().eq("is_mch",1).eq("mpid",mpid).isNotNull("sid"));
        MerchantApp mapp = merchantAppService.selectOne(new EntityWrapper<MerchantApp>().eq("id",mpid));

        for(User muser:musers){
            String phone = muser.getPhone();
            if(Strings.isNullOrEmpty(phone)){
                continue;
            }
            if(muser.getSid()==null)continue;

            String password = "hky"+phone;

            logger.debug("======new password=" + password);


            muser.setUsername(phone);
            if(muser.getIsMch()==null||muser.getIsMch()!=1){
                muser.setIsMch(1);
                muser.setIsStaff(1);
            }else{
                muser.setIsMch(1);
                muser.setIsAdmin(1);
            }

            muser.setModifytime(new Date());
            muser.setState(1);

            Store store = storeService.selectById(muser.getSid());
            if(store==null)continue;
            muser.setUserType(31);// 默认商家专业版
            muser.setPhoto(store.getPic());

            muser.setSalt(muser.getGuid().substring(0, 24));
            muser.setPassword(ObjectUtil.getPwd(password, muser.getSalt(), 3));

            muser.updateById();

            UserRole userrole = new UserRole();
            userrole.setUserid(muser.getId());
            userrole.setRoleid(11l);// 默认1
            userrole.setState(1);// 默认1
            userrole.setMid(mapp.getMid());// 默认1
            userrole.setUid(muser.getId());// 默认1
            userrole.insert();

            String msg = "请牢记账号密码：账号=" + phone + "，密码=" + password;
            jinfo.setInfo(msg);
        }


        return jinfo;
    }

}
